/**
 * API 统一导出文件
 * 
 * 提供两种使用方式：
 * 1. 向后兼容：import apiService from '@/utils/api-service.js'
 * 2. 模块化：import { authAPI, userAPI } from '@/utils/api/index.js'
 */

import baseAPI from './base.js'
import authAPI from './auth.js'
import userAPI from './user.js'
import friendAPI from './friend.js'
import chatAPI from './chat.js'
import adminAPI from './admin.js'
import syncAPI from './sync.js'

/**
 * 创建向后兼容的 APIService 类
 * 将所有模块的方法聚合到一个对象中
 */
class APIService {
    constructor() {
        // 保留原有的构造器属性（从 baseAPI 继承）
        this.baseURL = baseAPI.baseURL;
        this.environmentInfo = baseAPI.environmentInfo;
        this.retryCount = baseAPI.retryCount;
        this.maxRetries = baseAPI.maxRetries;
        this.retryDelay = baseAPI.retryDelay;
    }

    // ==================== 基础请求方法 ====================
    getPlatform() { return baseAPI.getPlatform(); }
    getNetworkInfo() { return baseAPI.getNetworkInfo(); }
    get(url, options) { return baseAPI.get(url, options); }
    request(url, options) { return baseAPI.request(url, options); }
    requestHealthCheck() { return baseAPI.requestHealthCheck(); }
    delay(ms) { return baseAPI.delay(ms); }
    getServerStatus() { return baseAPI.getServerStatus(); }
    refreshServerStatus() { return baseAPI.refreshServerStatus(); }
    onServerStatusChange(callback) { return baseAPI.onServerStatusChange(callback); }
    onStatusChange(callback) { return baseAPI.onStatusChange(callback); }
    offStatusChange(callback) { return baseAPI.offStatusChange(callback); }

    // ==================== 认证模块 ====================
    register(userData) { return authAPI.register(userData); }
    login(credentials) { return authAPI.login(credentials); }
    handleLocalRegister(userData) { return authAPI.handleLocalRegister(userData); }
    handleLocalLogin(credentials) { return authAPI.handleLocalLogin(credentials); }

    // ==================== 用户模块 ====================
    searchUsers(keyword) { return userAPI.searchUsers(keyword); }
    getUserInfo(email) { return userAPI.getUserInfo(email); }
    getUserById(userId) { return userAPI.getUserById(userId); }
    updateUserInfo(email, userData) { return userAPI.updateUserInfo(email, userData); }
    updateAvatar(email, avatarURL) { return userAPI.updateAvatar(email, avatarURL); }
    getUserCount() { return userAPI.getUserCount(); }
    getUserSettings(email) { return userAPI.getUserSettings(email); }
    updateUserSettings(email, settings) { return userAPI.updateUserSettings(email, settings); }
    getUserByEmail(email) { return userAPI.getUserByEmail(email); }
    getUserId(userData) { return userAPI.getUserId(userData); }
    getLocalUsers() { return userAPI.getLocalUsers(); }
    saveLocalUsers(users) { return userAPI.saveLocalUsers(users); }
    getLocalUserCount() { return userAPI.getLocalUserCount(); }
    generateOfflineId() { return userAPI.generateOfflineId(); }
    generateUserId() { return userAPI.generateUserId(); }

    // ==================== 好友模块 ====================
    addFriend(userId, friendId) { return friendAPI.addFriend(userId, friendId); }
    getFriends(userId) { return friendAPI.getFriends(userId); }
    deleteFriend(userId, friendId) { return friendAPI.deleteFriend(userId, friendId); }
    sendFriendRequest(fromUserId, toUserId, message) { return friendAPI.sendFriendRequest(fromUserId, toUserId, message); }
    getFriendRequests(userId, type) { return friendAPI.getFriendRequests(userId, type); }
    respondToFriendRequest(requestId, userId, action) { return friendAPI.respondToFriendRequest(requestId, userId, action); }
    cancelFriendRequest(requestId, userId) { return friendAPI.cancelFriendRequest(requestId, userId); }
    handleLocalGetFriends(options) { return friendAPI.handleLocalGetFriends(options); }
    handleLocalSendFriendRequest(body) { return friendAPI.handleLocalSendFriendRequest(body); }
    handleLocalGetFriendRequests(options) { return friendAPI.handleLocalGetFriendRequests(options); }

    // ==================== 聊天模块 ====================
    getUserRooms(userId) { return chatAPI.getUserRooms(userId); }
    createRoom(params) { return chatAPI.createRoom(params); }

    // ==================== 管理员模块 ====================
    getAdminUserList(params) { return adminAPI.getAdminUserList(params); }
    getAdminUserStats() { return adminAPI.getAdminUserStats(); }
    updateUserRole(userId, role) { return adminAPI.updateUserRole(userId, role); }
    banUser(userId, status, reason) { return adminAPI.banUser(userId, status, reason); }
    getUserRole(userId) { return adminAPI.getUserRole(userId); }
    getRoles() { return adminAPI.getRoles(); }
    getAdminAnnouncementList(params) { return adminAPI.getAdminAnnouncementList(params); }
    createAnnouncement(announcementData) { return adminAPI.createAnnouncement(announcementData); }
    updateAnnouncement(announcementId, updateData) { return adminAPI.updateAnnouncement(announcementId, updateData); }
    publishAnnouncement(announcementId) { return adminAPI.publishAnnouncement(announcementId); }
    deleteAnnouncement(announcementId) { return adminAPI.deleteAnnouncement(announcementId); }
    getSystemLogs(params) { return adminAPI.getSystemLogs(params); }
    getSystemInfo() { return adminAPI.getSystemInfo(); }

    // ==================== 数据同步模块 ====================
    syncDataFromServer() { return syncAPI.syncDataFromServer(); }
    checkDataSync() { return syncAPI.checkDataSync(); }
    getAllLocalData() { return syncAPI.getAllLocalData(); }
    saveSyncedData(data) { return syncAPI.saveSyncedData(data); }
    syncDataToServer(data, password) { return syncAPI.syncDataToServer(data, password); }

    // ==================== 本地头像更新（保留兼容） ====================
    handleLocalAvatarUpdate(body) {
        try {
            const requestData = JSON.parse(body);
            const { email, avatar } = requestData;
            
            if (!email || !avatar) {
                return Promise.reject(new Error('邮箱和头像数据不能为空'));
            }
            
            // 获取本地用户数据
            const users = this.getLocalUsers();
            console.log('本地用户列表:', users.map(u => ({ id: u.id, email: u.email, name: u.name })));
            console.log('查找用户邮箱:', email);
            
            const userIndex = users.findIndex(u => u.email === email);
            
            if (userIndex === -1) {
                console.log('本地用户不存在，可用邮箱:', users.map(u => u.email));
                return Promise.reject(new Error('用户不存在'));
            }
            
            // 更新用户头像
            users[userIndex].avatar = avatar;
            users[userIndex].updated_at = new Date().toISOString();
            
            // 保存到本地存储
            uni.setStorageSync('users', JSON.stringify(users));
            
            // 更新当前用户信息
            const currentUser = uni.getStorageSync('currentUser');
            if (currentUser) {
                const currentUserData = JSON.parse(currentUser);
                console.log('当前用户信息:', { email: currentUserData.email, name: currentUserData.name });
                if (currentUserData.email === email) {
                    currentUserData.avatar = avatar;
                    uni.setStorageSync('currentUser', JSON.stringify(currentUserData));
                    console.log('已更新当前用户头像');
                } else {
                    console.log('当前用户邮箱不匹配:', currentUserData.email, 'vs', email);
                }
            } else {
                console.log('未找到当前用户信息');
            }
            
            console.log('本地头像更新成功:', email);
            return Promise.resolve({
                code: 'SUCCESS',
                message: '头像更新成功（本地模式）',
                data: {
                    user: users[userIndex]
                }
            });
        } catch (error) {
            console.error('本地头像更新失败:', error);
            return Promise.reject(new Error('本地头像更新失败: ' + error.message));
        }
    }

    // 本地根据ID获取用户信息
    handleLocalGetUserById(url) {
        try {
            // 从URL中提取用户ID
            const userId = url.split('/users/id/')[1];
            
            if (!userId) {
                return Promise.reject(new Error('用户ID参数缺失'));
            }
            
            // 从本地存储中查找用户信息
            const users = this.getLocalUsers();
            const user = users.find(u => u.id == userId);
            
            if (!user) {
                return Promise.reject(new Error('用户不存在'));
            }
            
            return Promise.resolve({
                code: 'SUCCESS',
                message: '获取用户信息成功',
                data: user
            });
        } catch (error) {
            return Promise.reject(new Error('获取本地用户信息失败: ' + error.message));
        }
    }
}

// 创建全局 APIService 实例（向后兼容）
const apiService = new APIService();

// 默认导出（向后兼容原有的 import apiService from '@/utils/api-service.js'）
export default apiService;

// 导出各个独立模块（新的模块化用法）
export {
    baseAPI,
    authAPI,
    userAPI,
    friendAPI,
    chatAPI,
    adminAPI,
    syncAPI
}; 